<template>
	<view class="task-stats-container">
		<!-- 顶部维度指示器 -->
		<view class="dimension-indicator">
			<view class="dimension-tabs">
				<view v-for="dimension in timeDimensions" :key="dimension.value" 
					:class="['dimension-tab', { active: activeDimension === dimension.value }]"
					@tap="switchToDimension(dimension.value)">
					{{ dimension.label }}
				</view>
			</view>
		</view>

		<!-- 主内容区域 - 水平滑动的swiper -->
		<swiper class="main-swiper" horizontal="true" circular="false" :current="getDimensionIndex(activeDimension)" @change="onSwiperChange" :disable-scroll="false">
			<!-- 全部维度 -->
			<swiper-item class="swiper-slide" :key="'all'">
				<scroll-view scroll-y="true" class="slide-scroll-view">
					<view class="slide-content">
						<view v-if="isLoading" class="loading-container">
							<text class="loading-text">数据加载中...</text>
						</view>
						<view v-else-if="allDimensionStats.length > 0" class="stats-section">
							<view class="section-title">全部统计数据</view>
							<view class="stats-card-group">
								<view v-for="stat in allDimensionStats" :key="stat.type" class="stats-card">
									<view class="stats-card-header">
										<text class="stats-card-title">{{ getStatLabel(stat.type) }}统计</text>
									</view>
									<view class="stats-card-body">
										<view class="stats-item">
											<text class="stats-item-label">已完成任务</text>
											<text
												class="stats-item-value stats-item-value--completed">{{ stat.completedTasks }}</text>
										</view>
										<view class="stats-item">
											<text class="stats-item-label">待完成任务</text>
											<text class="stats-item-value stats-item-value--pending">{{ stat.pendingTasks }}</text>
										</view>
										<view class="stats-item">
											<text class="stats-item-label">总任务数</text>
											<text
												class="stats-item-value stats-item-value--total">{{ stat.completedTasks + stat.pendingTasks }}</text>
										</view>
										<view class="stats-item">
											<text class="stats-item-label">完成率</text>
											<text
												class="stats-item-value stats-item-value--rate">{{ calculateCompletionRate(stat) }}%</text>
										</view>
									</view>
									<view class="stats-card-footer">
										<view class="progress-bar">
											<view class="progress progress--completed"
												:style="{ 'width': calculateCompletionRate(stat) + '%' }"></view>
											<view class="progress progress--pending"
												:style="{ 'width': (100 - calculateCompletionRate(stat)) + '%' }"></view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-container">
							<text class="empty-text">暂无统计数据</text>
						</view>
					</view>
				</scroll-view>
			</swiper-item>

			<!-- 周维度 -->
			<swiper-item class="swiper-slide" :key="'week'">
				<scroll-view scroll-y="true" class="slide-scroll-view">
					<view class="slide-content">
						<view v-if="isLoading" class="loading-container">
							<text class="loading-text">数据加载中...</text>
						</view>
						<view v-else-if="weekStats" class="stats-section">
							<view class="section-title">本周统计数据</view>
							<view class="stats-card">
								<view class="stats-card-header">
									<text class="stats-card-title">本周任务完成情况</text>
								</view>
								<view class="stats-card-body">
									<view class="stats-item">
										<text class="stats-item-label">已完成任务</text>
										<text
											class="stats-item-value stats-item-value--completed">{{ weekStats.completedTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">待完成任务</text>
										<text class="stats-item-value stats-item-value--pending">{{ weekStats.pendingTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">总任务数</text>
										<text
											class="stats-item-value stats-item-value--total">{{ weekStats.completedTasks + weekStats.pendingTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">完成率</text>
										<text
											class="stats-item-value stats-item-value--rate">{{ calculateCompletionRate(weekStats) }}%</text>
									</view>
								</view>
								<view class="stats-card-footer">
									<view class="progress-bar">
										<view class="progress progress--completed"
											:style="{ 'width': calculateCompletionRate(weekStats) + '%' }"></view>
										<view class="progress progress--pending"
											:style="{ 'width': (100 - calculateCompletionRate(weekStats)) + '%' }"></view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-container">
							<text class="empty-text">暂无本周统计数据</text>
						</view>
					</view>
				</scroll-view>
			</swiper-item>

			<!-- 月维度 -->
			<swiper-item class="swiper-slide" :key="'month'">
				<scroll-view scroll-y="true" class="slide-scroll-view">
					<view class="slide-content">
						<view v-if="isLoading" class="loading-container">
							<text class="loading-text">数据加载中...</text>
						</view>
						<view v-else-if="monthStats" class="stats-section">
							<view class="section-title">本月统计数据</view>
							<view class="stats-card">
								<view class="stats-card-header">
									<text class="stats-card-title">本月任务完成情况</text>
								</view>
								<view class="stats-card-body">
									<view class="stats-item">
										<text class="stats-item-label">已完成任务</text>
										<text
											class="stats-item-value stats-item-value--completed">{{ monthStats.completedTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">待完成任务</text>
										<text class="stats-item-value stats-item-value--pending">{{ monthStats.pendingTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">总任务数</text>
										<text
											class="stats-item-value stats-item-value--total">{{ monthStats.completedTasks + monthStats.pendingTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">完成率</text>
										<text
											class="stats-item-value stats-item-value--rate">{{ calculateCompletionRate(monthStats) }}%</text>
									</view>
								</view>
								<view class="stats-card-footer">
									<view class="progress-bar">
										<view class="progress progress--completed"
											:style="{ 'width': calculateCompletionRate(monthStats) + '%' }"></view>
										<view class="progress progress--pending"
											:style="{ 'width': (100 - calculateCompletionRate(monthStats)) + '%' }"></view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-container">
							<text class="empty-text">暂无本月统计数据</text>
						</view>
					</view>
				</scroll-view>
			</swiper-item>

			<!-- 年维度 -->
			<swiper-item class="swiper-slide" :key="'year'">
				<scroll-view scroll-y="true" class="slide-scroll-view">
					<view class="slide-content">
						<view v-if="isLoading" class="loading-container">
							<text class="loading-text">数据加载中...</text>
						</view>
						<view v-else-if="yearStats" class="stats-section">
							<view class="section-title">本年统计数据</view>
							<view class="stats-card">
								<view class="stats-card-header">
									<text class="stats-card-title">本年任务完成情况</text>
								</view>
								<view class="stats-card-body">
									<view class="stats-item">
										<text class="stats-item-label">已完成任务</text>
										<text
											class="stats-item-value stats-item-value--completed">{{ yearStats.completedTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">待完成任务</text>
										<text class="stats-item-value stats-item-value--pending">{{ yearStats.pendingTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">总任务数</text>
										<text
											class="stats-item-value stats-item-value--total">{{ yearStats.completedTasks + yearStats.pendingTasks }}</text>
									</view>
									<view class="stats-item">
										<text class="stats-item-label">完成率</text>
										<text
											class="stats-item-value stats-item-value--rate">{{ calculateCompletionRate(yearStats) }}%</text>
									</view>
								</view>
								<view class="stats-card-footer">
									<view class="progress-bar">
										<view class="progress progress--completed"
											:style="{ 'width': calculateCompletionRate(yearStats) + '%' }"></view>
										<view class="progress progress--pending"
											:style="{ 'width': (100 - calculateCompletionRate(yearStats)) + '%' }"></view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-container">
							<text class="empty-text">暂无本年统计数据</text>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed } from 'vue';
	import { StatsItem } from '../../../types/task';
	import { listStatsAPI } from '../../../services/task';

	/**
	 * 统计数据数组（过滤后显示的数据）
	 */
	const statistics = ref<StatsItem[]>([]);

	/**
	 * 原始统计数据数组（完整数据）
	 */
	const originalStatistics = ref<StatsItem[]>([]);

	/**
	 * 数据加载状态
	 */
	const isLoading = ref(true);

	/**
	 * 时间维度选项
	 */
	const timeDimensions = ref([
		{
			label: '全部',
			value: 'all'
		},
		{
			label: '周',
			value: 'week'
		},
		{
			label: '月',
			value: 'month'
		},
		{
			label: '年',
			value: 'year'
		}
	]);

	/**
	 * 当前激活的时间维度
	 */
	const activeDimension = ref('all');

	/**
	 * 根据维度筛选的数据计算属性
	 */
	const allDimensionStats = computed(() => {
		return statistics.value.filter(stat => stat && typeof stat.type === 'number');
	});

	const weekStats = computed(() => {
		return statistics.value.find(stat => stat && stat.type === 1);
	});

	const monthStats = computed(() => {
		return statistics.value.find(stat => stat && stat.type === 2);
	});

	const yearStats = computed(() => {
		return statistics.value.find(stat => stat && stat.type === 3);
	});

	/**
	 * 获取时间维度对应的索引
	 */
	const getDimensionIndex = (dimension: string) => {
		return timeDimensions.value.findIndex(item => item.value === dimension);
	};

	/**
	 * 处理swiper切换
	 */
	const onSwiperChange = (e: any) => {
		const index = e.detail.current;
		if (timeDimensions.value[index]) {
			activeDimension.value = timeDimensions.value[index].value;
		}
	};

	/**
	 * 切换到指定维度
	 */
	const switchToDimension = (dimension: string) => {
		activeDimension.value = dimension;
	};

	/**
	 * 计算任务完成率
	 * @param stat 统计项数据
	 * @returns 完成率百分比
	 */
	const calculateCompletionRate = (stat : StatsItem | null | undefined) : number => {
		// 检查参数是否有效
		if (!stat) {
			return 0;
		}

		// 处理可能的undefined值
		const completedTasks = stat.completedTasks || 0;
		const pendingTasks = stat.pendingTasks || 0;
		const totalTasks = completedTasks + pendingTasks;

		// 避免除以0
		if (totalTasks === 0) {
			return 0;
		}

		// 计算完成率并四舍五入到整数
		return Math.round((completedTasks / totalTasks) * 100);
	};

	/**
	 * 获取统计标签
	 * @param type 统计类型
	 * @returns 统计标签文本
	 */
	const getStatLabel = (type : number | null | undefined) : string => {
		// 处理无效参数
		if (type === null || type === undefined || typeof type !== 'number') {
			return '未知';
		}

		switch (type) {
			case 1:
				return '本周';
			case 2:
				return '本月';
			case 3:
				return '本年';
			default:
				return '未知';
		}
	};

	/**
	 * 调用任务统计API获取数据
	 * @returns 任务统计数据数组
	 */
	const getTaskStatsAPI = async () : Promise<StatsItem[]> => {
		try {
			const result = await listStatsAPI();
			// 检查返回数据格式，确保正确提取统计数据数组
			// 处理常见的API响应格式：{code: 0, msg: 'success', data: [...]}  
			let statsArray: any[] = [];
			
			if (Array.isArray(result)) {
				// 如果直接返回数组
				statsArray = result;
			} else if (result && typeof result === 'object' && Array.isArray(result.data)) {
				// 如果返回对象，且包含data数组字段
				statsArray = result.data;
			} else {
				console.warn('API返回的数据格式不符合预期，返回空数组');
				return [];
			}
			
			// 过滤掉null和undefined值
			return statsArray.filter(item => item !== null && item !== undefined);
		} catch (error) {
			console.error('获取任务统计数据失败:', error);
			return []; // 出错时返回空数组，避免页面白屏
		}
	};

	/**
	 * 加载任务统计数据
	 * @returns Promise<void>
	 */
	const loadTaskStatsData = async () : Promise<void> => {
		try {
			isLoading.value = true;
			const result = await getTaskStatsAPI();
			// 确保result是有效的数组
			if (Array.isArray(result)) {
				originalStatistics.value = [...result]; // 使用展开运算符创建新数组
				statistics.value = [...result];
			} else {
				console.warn('获取的数据格式异常，重置为默认值');
				originalStatistics.value = [];
				statistics.value = [];
			}
		} catch (error) {
			console.error('加载任务统计数据失败:', error);
			// 出错时重置为默认值
			originalStatistics.value = [];
			statistics.value = [];
		} finally {
			isLoading.value = false;
		}
	};

	/**
	 * 处理页面导航
	 * @param url 目标页面URL
	 */
	const handleNavigation = (url : string) : void => {
		// 如果已经是当前页面，则不执行导航
		if (url === '/pages/task/stats/stats') {
			return;
		}
		uni.navigateTo({
			url
		});
	};

	// 页面加载时获取数据
	onMounted(() => {
		loadTaskStatsData();
	});
</script>

<style lang="scss" scoped>
	// 全局样式变量
	$primary-color: #4CAF50;
	$bg-color: #f9f9f9;
	$text-color: #333;
	$text-secondary: #666;
	$border-radius: 10px;
	$nav-height: 60px;
	$completed-color: #4CAF50;
	$pending-color: #FF9800;

	// 新增主题变量（更商业化的观感）
	$bg-gradient: linear-gradient(135deg, #f7fafc 0%, #edf2f7 40%, #eef5ff 100%);
	$card-bg: linear-gradient(180deg, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.9));
	$card-border: rgba(255, 255, 255, 0.6);
	$shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
	$shadow-hover: 0 10px 24px rgba(0, 0, 0, 0.12);
	$tab-bg: rgba(255, 255, 255, 0.6);
	$tab-active-gradient: linear-gradient(135deg, #34d399, #10b981);
	$track-color: #e6eaf0;

	// 容器样式
	.task-stats-container {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: $bg-gradient;
		background-attachment: fixed;
	}

	// 顶部维度指示器
	.dimension-indicator {
		background: transparent;
		padding: 12px 0;
		position: sticky;
		top: 0;
		z-index: 10;
		backdrop-filter: saturate(180%) blur(10px);
	}

	.dimension-tabs {
		display: flex;
		justify-content: center;
		padding: 0 20px;
		position: relative;
	}

	.dimension-tab {
		padding: 10px 22px;
		margin: 0 6px;
		border-radius: 999px;
		font-size: 0.95rem;
		color: $text-secondary;
		transition: all 0.25s ease;
		background: $tab-bg;
		border: 1px solid rgba(255,255,255,0.7);
		box-shadow: 0 2px 8px rgba(27, 31, 35, 0.05);
		backdrop-filter: blur(6px);
	}

	.dimension-tab:active {
		transform: translateY(1px);
	}

	.dimension-tab.active {
		background: $tab-active-gradient;
		color: white;
		box-shadow: 0 6px 14px rgba(16, 185, 129, 0.28);
		border-color: transparent;
	}

	// 主内容swiper
	.main-swiper {
		flex: 1;
		width: 100%;
	}

	.swiper-slide {
		width: 100%;
		height: 100%;
	}

	// 滑动视图
	.slide-scroll-view {
		width: 100%;
		height: 100%;
	}

	.slide-content {
		padding: 20px;
		padding-bottom: $nav-height;
		max-width: 980px;
		margin: 0 auto;
	}

	// 加载状态样式
	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200px;
	}

	.loading-text {
		color: $text-secondary;
		font-size: 1rem;
		letter-spacing: 0.2px;
	}

	// 空状态样式
	.empty-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200px;
	}

	.empty-text {
		color: $text-secondary;
		font-size: 1rem;
		letter-spacing: 0.2px;
	}

	// 统计区域样式
	.stats-section {
		display: flex;
		flex-direction: column;
		gap: 20px;
	}

	.section-title {
		font-size: 1.2rem;
		font-weight: 700;
		color: $text-color;
		margin-bottom: 6px;
		letter-spacing: 0.3px;
	}

	// 统计卡片组样式
	.stats-card-group {
		display: flex;
		flex-direction: column;
		gap: 15px;
	}

	// 统计卡片样式
	.stats-card {
		background: $card-bg;
		border-radius: $border-radius + 4px;
		padding: 20px 20px 18px 20px;
		box-shadow: $shadow;
		border: 1px solid $card-border;
		backdrop-filter: blur(8px);
		transition: transform 0.2s ease, box-shadow 0.2s ease;
	}

	.stats-card:hover {
		transform: translateY(-2px);
		box-shadow: $shadow-hover;
	}

	// 卡片头部样式
	.stats-card-header {
		margin-bottom: 14px;
	}

	.stats-card-title {
		font-size: 1.14rem;
		font-weight: 700;
		color: $text-color;
		letter-spacing: 0.3px;
	}

	// 卡片主体样式
	.stats-card-body {
		display: flex;
		flex-direction: column;
		gap: 8px;
		margin-bottom: 14px;
	}

	// 统计项样式
	.stats-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 0;
	}

	.stats-item-label {
		font-size: 0.92rem;
		color: $text-secondary;
		letter-spacing: 0.2px;
	}

	// 统计值样式
	.stats-item-value {
		font-size: 1.18rem;
		font-weight: 700;
		letter-spacing: 0.2px;
	}

	// 不同状态的统计值颜色
	.stats-item-value--completed {
		color: $completed-color;
	}

	.stats-item-value--pending {
		color: $pending-color;
	}

	.stats-item-value--total {
		color: $text-color;
	}

	.stats-item-value--rate {
		color: $primary-color;
	}

	// 卡片底部样式
	.stats-card-footer {
		display: flex;
		justify-content: center;
	}

	// 进度条样式
	.progress-bar {
		display: flex;
		width: 100%;
		height: 12px;
		border-radius: 999px;
		overflow: hidden;
		background-color: $track-color;
		border: 1px solid rgba(0, 0, 0, 0.04);
	}

	// 进度条分段样式
	.progress {
		height: 100%;
		transition: width 0.5s ease;
	}

	// 已完成进度条样式
	.progress--completed {
		background: linear-gradient(90deg, #34d399, #10b981);
		box-shadow: inset 0 0 0 1px rgba(0,0,0,0.02);
	}

	// 待完成进度条样式
	.progress--pending {
		background-color: transparent;
	}
</style>